//
//  SWComposeController.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/3/8.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit

class SWComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        //SetUI
        setUpUI()
        //监听键盘的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    deinit {
        //移除监听
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK:监听键盘回调方法
    func keyBoardWillChangeFrame(notification:NSNotification) {
        
        //动画时间
        let duration = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        //键盘最终的frame
        let frame = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        //设置toolbar的位置 重新约束
        let toolBarBottomCon = -(UIScreen.height - frame.origin.y)
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(toolBarBottomCon)
        }
        //加动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    //MARK:设置UI
    private func setUpUI() {
        setUpTitleView()
        setNavButtonItem()
        setUpTextView()
        setUpToolBar()
    }
    
    //设置textview
    private func setUpTextView() {
        
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
    }
    //设置toolbar
    func setUpToolBar() {
        
        view.addSubview(toolBar)
        //添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        
        toolBar.items = [UIBarButtonItem]()
        //for遍历出item
        for dict in itemSettings {
            //item的图片
            let imageName = dict["imageName"]
            let item = UIBarButtonItem(imageName: imageName!)
            //加入item
            toolBar.items?.append(item)
            
            let button = item.customView as! UIButton
            let action = dict["action"]!
            //添加点击事件
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            //添加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后的弹簧
        toolBar.items?.removeLast()
    }
    
    func setUpTitleView() {
        let prefix = "发微博"
        //拿到用户的名字
        if let name = SWUserAccountViewModel.sharedInstance.userAccount?.screen_name {
            let title = prefix + "\n" + name
            //创建titlelabel
            let titleLabel  = UILabel()
            titleLabel.font = UIFont.systemFontOfSize(14)
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = NSTextAlignment.Center
            
            //设置为可变的字符串属性
            let attrText = NSMutableAttributedString(string: title)
            //设定范围为name
            let range = (title as NSString).rangeOfString(name)
            //添加属性
            attrText.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor() , NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range)
            
            titleLabel.attributedText = attrText
            
            titleLabel.sizeToFit()
            //设定titleview
            navigationItem.titleView = titleLabel
        }else {
            navigationItem.title = prefix
        }
        
    }
    
    
    //MARK: 按钮回调
    @objc private func close() {
        //textView取消第一响应者
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发微博
    func send() {
    
    }
    
    private func setNavButtonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        //发送按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    
    
    func picture() {
        print("图片")
    }
    func trend() {
        print("#")
    }
    func mention() {
        print("@")
    }
    func emoticon() {
        print("表情")
    }
    func add() {
        print("+")
    }
    
    //MARK: 懒加载
    private lazy var textView: SWPlaceholderTextView = {
        let placeTextView = SWPlaceholderTextView()
        //总是能垂直拖动
        placeTextView.alwaysBounceVertical = true
        placeTextView.font = UIFont.systemFontOfSize(18)
        
        //textView键盘退出的方法
        placeTextView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        placeTextView.placeholder = "分享新鲜事..."
        //设定代理
        placeTextView.delegate = self
        return placeTextView
    }()
    
    private lazy var toolBar: UIToolbar = {
        let toolbar = UIToolbar()
        return toolbar
    }()
}

//MARK: textView代理
extension SWComposeController: UITextViewDelegate {
    //当用户有输入东西时 发送按钮可用
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
